<?php

namespace app\api\controller\user;

use app\api\controller\BaseController;
use app\api\model\Setting as SettingModel;
use app\common\library\storage\Driver as StorageDriver;
use app\common\model\user\UserRealModel;
use app\utils\aliyun\OcrIdcard;
use app\utils\aliyun\VerifyIdName;
use GuzzleHttp\Exception\GuzzleException;
use think\Exception;

class UserReal extends BaseController
{
    
    protected UserRealModel $model;
    
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = new UserRealModel();
    }
    
    /**
     * 获取 政治面貌 字段枚举 列表
     * @return array
     */
    public function getOutlookEnumList(): array
    {
        // return $this->renderSuccess($this->model->getOutlookEnumList());
        return $this->renderSuccess(array_values($this->model->getOutlookEnumList()));
    }
    
    /**
     * 获取 文化程度 字段枚举 列表
     * @return array
     */
    public function getEducationEnumList(): array
    {
        // return $this->renderSuccess($this->model->getEducationEnumList());
        return $this->renderSuccess(array_values($this->model->getEducationEnumList()));
    }
    
    /**
     * 获取 退休状态 字段枚举 列表
     * @return array
     */
    public function getRetireStatusEnumList(): array
    {
        // return $this->renderSuccess($this->model->getRetireStatusEnumList());
        return $this->renderSuccess(array_values($this->model->getRetireStatusEnumList()));
    }
    
    /**
     * 获取 单位类型 字段枚举 列表
     * @return array
     */
    public function getCompanyCategoryIdEnumList(): array
    {
        // return $this->renderSuccess($this->model->getCompanyCategoryIdEnumList());
        return $this->renderSuccess(array_values($this->model->getCompanyCategoryIdEnumList()));
    }
    
    protected function img()
    {
        // 实例化存储驱动
        $StorageDriver = new StorageDriver(SettingModel::getItem('storage'));
        // 设置上传文件的信息
        $StorageDriver->setUploadFile('idCardImg');
        // 上传图片
        if (!$StorageDriver->upload()) {
            return json(['code' => 0, 'msg' => '图片上传失败' . $StorageDriver->getError()]);
        }
        return $StorageDriver->getFilePath();
    }
    
    /**
     * 上传并识别 身份证正面
     * @return array
     * @throws \think\Exception
     */
    public function verifyIdCardFrontImg(): array
    {
        $imgUrl = $this->img();
        $verify = OcrIdcard::instance()->verifyIdCardFrontImg($this->request->domain() . $imgUrl);
        if ($verify->noServe) {
            unlink(WEB_PATH . $imgUrl);
            return $this->renderError('认证服务暂不可用，请联系管理员！',[$verify,$imgUrl]);
        }
        if (!$verify->verify) {
            unlink(WEB_PATH . $imgUrl);
            return $this->renderError('身份证正面识别失败,请上传完整清晰的身份证正面',[$verify,$imgUrl]);
        }
        $verify = $verify->result;
        $data = [
            'user_id' => $this->user['user_id'],
            'realName' => $verify->name,
            'gender' => $verify->sex == '男' ? 1 : 0,
            'nation' => $verify->nation,
            'year' => $verify->year,
            'month' => $verify->month,
            'day' => $verify->day,
            'id_card_address' => $verify->address,
            'id_card' => $verify->number,
            'id_card_front_img' => $imgUrl,
        ];
        $userReal = $this->model->getUserReal($data['id_card']);
        if ($userReal) {
            unlink(WEB_PATH . $imgUrl);
            return $this->renderError('身份证号码已被认证,若是非您本人认证，请联系管理员处理！');
        }
        if (!VerifyIdName::instance()->verify($data['id_card'], $data['realName'])) {
            unlink(WEB_PATH . $imgUrl);
            return $this->renderError('实名认证失败,请您检查核对身份信息重新提交认证！');
        }
        $userRealModel = $this->model->saveData($data);
        if (!empty($userRealModel['id_card_front_img']) && !empty($userRealModel['id_card_back_img'])) {
            $data['real_verify'] = 1;
        }
        $userRealModel = $this->model->saveData($data);
        return $this->renderSuccess($userRealModel,'恭喜您实名认证成功！');
    }
    
    /**
     * 上传并识别 身份证反面
     * @return array
     * @throws \think\Exception
     */
    public function verifyIdCardBackImg(): array
    {
        $imgUrl = $this->img();
        $verify = OcrIdcard::instance()->verifyIdCardFrontImg($this->request->domain() . '/' . $imgUrl);
        if ($verify->noServe) {
            unlink(WEB_PATH . $imgUrl);
            return $this->renderError('认证服务暂不可用，请联系管理员！',[$verify,$imgUrl]);
        }
        if ($verify->verify === false) {
            unlink(WEB_PATH . $imgUrl);
            return $this->renderError('身份证反面识别失败,请上传完整清晰的身份证反面',[$verify,$imgUrl]);
        }
        $verify = $verify->result;
        $data = [
            'user_id' => $this->user['user_id'],
            'authority' => $verify->authority,
            'timelimit' => $verify->timelimit,
            'id_card_back_img' => $imgUrl,
        ];
        
        $userRealModel = $this->model->saveData($data);
        if (!empty($userRealModel['id_card_front_img']) && !empty($userRealModel['id_card_back_img'])) {
            $data['real_verify'] = 1;
        }
        $userRealModel = $this->model->saveData($data);
        return $this->renderSuccess($userRealModel,'身份证反面识别成功');
    }
    
    /**
     * 实名认证
     * @return array
     * @throws GuzzleException
     * @throws Exception
     */
    public function verifyIdName(): array
    {
        $data = $this->request->param();
        $data['user_id'] = $this->user['user_id'];
        // todo 自动审核 2（通过） 手动审核 1（未审核）
        $data['verify'] = 2;
        
        $userRealModel = $this->model->saveData($data);
        return $this->renderSuccess($userRealModel, '保存成功');
    }
    
    public function detail(): array
    {
        $userRealModel = $this->model->detail($this->user['user_id']);
        return $this->renderSuccess($userRealModel);
    }
}